﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Portal
{
    public class HttpCache : ICache
    {
        #region Implementation of ICache

        protected static System.Web.Caching.Cache Cache
        {
            get { return HttpContext.Current.Cache; }
        }



        public int Count
        {
            get { return HttpContext.Current.Cache.Count; }
        }

        public void Clear()
        {
            var itemsToRemove = new List<string>();
            IDictionaryEnumerator enumerator = Cache.GetEnumerator();
            while (enumerator.MoveNext())
            {
                itemsToRemove.Add(enumerator.Key.ToString());
            }
            foreach (string itemToRemove in itemsToRemove)
                Cache.Remove(itemToRemove);
        }

        public bool Contains(string key)
        {
            Check.Argument.IsNotEmpty(key, "key");

            return Cache.Get(key) != null;
        }

        public T Get<T>(string key)
        {
            Check.Argument.IsNotEmpty(key, "key");
            return (T)Cache.Get(key);
        }

        public bool TryGet<T>(string key, out T value)
        {
            Check.Argument.IsNotEmpty(key, "key");
            value = default(T);
            object existingValue = Cache.Get(key);
            if (existingValue != null)
            {
                value = (T)existingValue;
                return true;
            }
            return false;
        }

        public void Set<T>(string key, T value)
        {
            Cache.Insert(key, value);
        }

        public void Set<T>(string key, T value, DateTime absoluteExpiration)
        {
            Cache.Insert(key, value);
        }

        public void Set<T>(string key, T value, TimeSpan slidingExpiration)
        {
            Cache.Insert(key, value);
        }

        public void Remove(string key)
        {
            Cache.Remove(key);
        }

        #endregion
    }
}
